<template>
  <div>
    <el-card :bordered="false" shadow="never" class="ivu-mb-16" :body-style="{ padding: 0 }">
      <div class="padding-add">
        <el-form
          ref="formValidate"
          :model="formValidate"
          label-width="80px"
          label-position="right"
          @submit.native.prevent
          inline
        >
          <el-form-item label="搜索：" label-for="name">
            <el-input clearable placeholder="请输入公司名称" v-model="formValidate.name" class="form_content_width" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getList">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-card :bordered="false" shadow="never" class="ivu-mt">
      <el-button type="primary" @click="showAddDialog">添加公司</el-button>

      <el-table
        :data="list"
        class="mt14"
        no-userFrom-text="暂无数据"
        no-filtered-userFrom-text="暂无筛选结果"
        v-loading="loading"
        highlight-current-row
      >
        <el-table-column label="ID" width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.id }}</span>
          </template>
        </el-table-column>

        <el-table-column label="公司名称" min-width="200">
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" fixed="right" width="100">
          <template slot-scope="scope">
            <a @click="editCompany(scope.row)">编辑</a>
            <el-divider direction="vertical"></el-divider>
            <a @click="deleteCompany(scope.row)">删除</a>
          </template>
        </el-table-column>
      </el-table>

      <div class="acea-row row-right page">
        <pagination
          v-if="total"
          :total="total"
          :page.sync="formValidate.page"
          :limit.sync="formValidate.limit"
          @pagination="getList"
        />
      </div>
    </el-card>

    <!-- 添加/编辑公司对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" @close="resetForm">
      <el-form ref="companyForm" :model="companyForm" :rules="rules" label-width="100px">
        <el-form-item label="公司名称" prop="name">
          <el-input v-model="companyForm.name" placeholder="请输入公司名称"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { getCompanyList, addCompany } from '@/api/seed';

export default {
  name: 'CompanyManage',
  data() {
    return {
      total: 0,
      loading: false,
      submitLoading: false,
      formValidate: {
        name: '',
        page: 1,
        limit: 20,
      },
      list: [],
      dialogVisible: false,
      dialogTitle: '添加公司',
      isEdit: false,
      companyForm: {
        id: null,
        name: '',
      },
      rules: {
        name: [
          { required: true, message: '请输入公司名称', trigger: 'blur' },
          { min: 2, max: 100, message: '公司名称长度在 2 到 100 个字符', trigger: 'blur' },
        ],
      },
    };
  },
  computed: {
    ...mapState('media', ['isMobile']),
    labelWidth() {
      return this.isMobile ? undefined : '100px';
    },
    labelPosition() {
      return this.isMobile ? 'top' : 'left';
    },
  },
  created() {
    this.getList();
  },
  methods: {
    // 获取公司列表
    getList() {
      this.loading = true;
      const params = {
        page: this.formValidate.page,
        limit: this.formValidate.limit,
      };

      // 如果有搜索条件，添加到参数中
      if (this.formValidate.name) {
        params.name = this.formValidate.name;
      }

      getCompanyList(params)
        .then((res) => {
          if (res.status === 200) {
            this.total = res.data.count;
            this.list = res.data.list;
          } else {
            this.$message.error(res.msg || '获取公司列表失败');
          }
          this.loading = false;
        })
        .catch((err) => {
          this.loading = false;
          this.$message.error(err.msg || '获取公司列表失败');
        });
    },

    // 显示添加公司对话框
    showAddDialog() {
      this.dialogTitle = '添加公司';
      this.isEdit = false;
      this.dialogVisible = true;
      this.resetForm();
    },

    // 编辑公司
    editCompany(row) {
      this.dialogTitle = '编辑公司';
      this.isEdit = true;
      this.companyForm = {
        id: row.id,
        name: row.name,
      };
      this.dialogVisible = true;
    },

    // 删除公司
    deleteCompany(row) {
      this.$confirm(`确定要删除公司"${row.name}"吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          // 这里需要调用删除接口，但题目中没有提供删除接口
          // 暂时只显示消息
          this.$message.info('删除功能需要后端提供删除接口');
        })
        .catch(() => {
          // 用户取消删除
        });
    },

    // 提交表单
    submitForm() {
      this.$refs.companyForm.validate((valid) => {
        if (valid) {
          this.submitLoading = true;

          if (this.isEdit) {
            // 编辑功能需要后端提供编辑接口
            this.$message.info('编辑功能需要后端提供编辑接口');
            this.submitLoading = false;
            return;
          }

          // 添加公司
          addCompany({ name: this.companyForm.name })
            .then((res) => {
              if (res.status === 200) {
                this.$message.success('添加公司成功');
                this.dialogVisible = false;
                this.getList(); // 重新获取列表
              } else {
                this.$message.error(res.msg || '添加公司失败');
              }
              this.submitLoading = false;
            })
            .catch((err) => {
              this.submitLoading = false;
              this.$message.error(err.msg || '添加公司失败');
            });
        }
      });
    },

    // 重置表单
    resetForm() {
      if (this.$refs.companyForm) {
        this.$refs.companyForm.resetFields();
      }
      this.companyForm = {
        id: null,
        name: '',
      };
    },
  },
};
</script>

<style scoped lang="scss">
.padding-add {
  padding: 20px;
}

.form_content_width {
  width: 200px;
}

.mt14 {
  margin-top: 14px;
}

.ivu-mb-16 {
  margin-bottom: 16px;
}

.ivu-mt {
  margin-top: 16px;
}

.acea-row {
  display: flex;

  &.row-right {
    justify-content: flex-end;
  }
}

.page {
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>
